<?php
	session_start();
	$connection = mysql_pconnect("localhost" , "root" , "31122001");
    mysql_select_db("kt_site");
	if (isset($_POST['submit'])){		
    	if(empty($_POST['username']) || empty($_POST['lastname']) || empty($_POST['firstname']) || empty($_POST['phonenumber']) || empty($_POST['email']) || empty($_POST['password']))  {
    		$_SESSION['error'] = "Some fields are empty!";
    		echo "<meta http-equiv='Refresh' content='0; URL=registration.php'>";	
    		exit;
		} elseif (!preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/", $_POST['email'])) {			
			$_SESSION['error'] = "Incorrect email address!";
    		echo "<meta http-equiv='Refresh' content='0; URL=registration.php'>";	
    		exit;
		} else {
			$username = $_POST['username'];
			$password = $_POST['password'];
			$mdPassword = md5($password);
			$password2 = $_POST['password2'];
			$email = $_POST['email'];			
			$lastname = $_POST['lastname'];  
			$firstname = $_POST['firstname'];
			$phonenumber = $_POST['phonenumber'];
			$confirmation_hash = substr($mdPassword , 0 , 30);
			$query = "SELECT id FROM users WHERE username = '".$username."';";
			$sql = mysql_query($query);

			if (mysql_num_rows($sql) > 0) {
				$_SESSION['error'] = "Such login already exists!";
	    		echo "<meta http-equiv='Refresh' content='0; URL=registration.php'>";	
	    		exit;
			} else {				
				$query = "INSERT INTO users (username, password, email, confirmation_hash, lastname, firstname, phonenumber) VALUES ('$username', '$mdPassword', '$email', '$confirmation_hash', '$lastname', '$firstname', '$phonenumber');";
				$result = mysql_query($query);
				if ($result) {
					$_SESSION['message'] = "New user successfully registered!";
		    		echo "<meta http-equiv='Refresh' content='0; URL=index.php'>";
		    		exit;
				}				
			}
		}
	} else if (isset($_POST['Cancel'])) {
		echo "<meta http-equiv='Refresh' content='0; URL=index.php'>";
		exit;
	}
?>